package com.example.myapplication.socket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.myapplication.bean.WifiDataBean;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ServerSocketStart extends Thread {
    private final String TAG = "ServerThread";
    private ServerSocket serverSocket;
    private boolean isServerRuning = false; //服务器是否在运行
    public Map<String, SocketThread> socketThreadMap = new HashMap<>(); //客户端列表  ip:端口，客户端
    private int port = 0;
    private Handler handler = null;
    public ServerSocketStart(Handler handler, int port) {
        this.handler = handler;
        this.port = port;
    }

    public void start() {
        try {
            serverSocket = new ServerSocket(port);
            isServerRuning = true;
            super.start();
            Log.e(TAG, "服务器运行成功");
        } catch (IOException e) {
            e.printStackTrace();
            isServerRuning = false;
            Log.e(TAG, "服务器运行失败");
        }
    }

    @Override
    public void interrupt() {
        isServerRuning = false;
        if (socketThreadMap != null) {
            Log.e(TAG, "客户端个数：" + socketThreadMap.size());
            Iterator<String> iterator = socketThreadMap.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                socketThreadMap.get(key).interrupt();
            }
            socketThreadMap.clear();
            socketThreadMap = null;
        }
        Log.e(TAG, "客户端资源释放完毕");
        //关闭服务器
        if (serverSocket != null) {
            try {
                serverSocket.close();
                serverSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e(TAG, "关闭服务器完毕");
        super.interrupt();
    }

    //获取服务器是否在运行
    public boolean isServerRuning() {
        return isServerRuning;
    }

    @Override
    public void run() {
        super.run();
        while (isServerRuning()) {
            try {
                Socket socket = serverSocket.accept(); //等待客户端连接
                Log.e(TAG, "有客户端连接上：" + socket.toString());
                if (socket != null) {
                    SocketThread socketThread = new SocketThread(socket);
                    socketThread.start();
                    Message msg = new Message();
                    msg.what = 0x127;
                    msg.obj = socket.getInetAddress()+":" +socket.getPort();
                    handler.sendMessage(msg);
                    socketThreadMap.put(socket.getInetAddress() + ":" + socket.getPort(), socketThread);
                }
            } catch (IOException e) {
//                e.printStackTrace();
            }
        }
    }

    //客户端线程
    class SocketThread extends Thread {
        Socket socket;
        InputStream inputStream;
        String key = "";

        public SocketThread(Socket socket) {
            key = socket.getInetAddress() + ":" + socket.getPort();
            this.socket = socket;
        }

        @Override
        public void interrupt() {
            if (socket != null) {
                try {
                    socket.close();
                    socket = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                this.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            super.interrupt();
        }

        @Override
        public void run() {

            while (true) {
                    try {
                        byte[] buffer = new byte[10000];
                        //获取输入流
                        DataInputStream input = new DataInputStream(socket.getInputStream());
                        int length = input.read(buffer);
                        String Msg = new String(buffer, 0, length, "UTF-8");
                        socket.shutdownInput();
                        /**
                         * ！！！！！坑
                         * 清洗数据 板子返回的数据不规则 截取{}的内容
                         */
                        Msg = Msg.substring(Msg.indexOf("{"), Msg.indexOf("}")+1);
                        /**
                         * 坑解决完毕
                         */

                        Message msg = new Message();
                        msg.what = 0x126;
                        msg.obj = Msg;
                        handler.sendMessage(msg);

                        Log.d(TAG,Msg);
                    } catch (Exception e) {
                        Log.e(TAG, "Server: Error");
                        e.printStackTrace();
                    } finally {
                        this.interrupt();
                        Log.e(TAG, "Server: Close:");

                    }
            }
        }
    }



}
